//
//  GGCyclicImg.m
//  ToolsDemo
//
//  Created by IOS on 2021/6/29.
//

#import "GGCyclicImg.h"

@interface GGCyclicImg ()
{
    CADisplayLink *_disLink;
    CGRect _frame;
    CGSize _imgSize;
    CGPoint _point;
    NSString *_img;
}
@end

@implementation GGCyclicImg

- (instancetype)initWithFrame:(CGRect)frame by:(NSString *)img {
    _img = img;
    return [self initWithFrame:frame];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _frame = frame;
        [self setUI];
    }
    return self;
}

- (void)setUI {
    // 1656 * 414 828 * 414
    CGFloat img_w = 828;
    CGFloat h = 414;
    NSString *imagBG = @"renting_sky";
    if ([BRThemeManage  isHasDark]) {
        imagBG = @"renting_sky3";
        img_w = 1566;
        h = 655;
    }
    
    UIImage *image = _img.length != 0 ? UIImageMake(_img) : UIImageMake(imagBG);
    if (_img.length != 0) {
        img_w = kScale414(image.size.width / 3.0);
        h = kScale414(image.size.height / 3.0);
    }
    
    for (int i = 0; i < 3; i++) {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(img_w * i, 0, img_w, h)];
        img.image = image;
        img.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:img];
    }
    self.contentSize = CGSizeMake(img_w * 3, 0);
    _imgSize = CGSizeMake(img_w, h);
    self.scrollEnabled = NO;
    self.bounces = NO;
    _disLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(scorellD)];
    _disLink.preferredFramesPerSecond = _img.length != 0 ? 30 : 60;
    [_disLink addToRunLoop:NSRunLoop.currentRunLoop forMode:NSDefaultRunLoopMode];
    
    if (@available(iOS 11.0, *)) {
        self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}


- (void)scorellD {
    _point = self.contentOffset;
    CGFloat speed = 1;
    if (self.isHorizontal) {
        if (_point.x < (_imgSize.width)) {
            _point.x += speed;
        }else {
            
            _point.x = speed;
        }
    }else {
        if (_point.y < (_imgSize.height)) {
            _point.y += speed;
        }else {
            
            _point.y = speed;
        }
    }
    
    
    self.contentOffset = _point;
}

- (void)dealloc {
    NSLog(@"GGCyclicImg dealloc");
    [_disLink invalidate];
    [_disLink removeFromRunLoop:NSRunLoop.currentRunLoop forMode:NSDefaultRunLoopMode];
}


@end
